import {Injectable} from "@angular/core";
import {Http, Response} from "@angular/http";
import {Observable} from "rxjs/Observable";

export class User {
    constructor(public id:number, public name:string) {
    }
}


@Injectable()
export class UserService {
    constructor(private http:Http) {
    }


    getUsers() {
        // return this.http.get(this.usersUrl).toPromise();
        return this.http.get('user/list').map(this.extractData).catch(this.handleError);
    }

    getUser(id:number) {
        return this.http.get('user/get?id=' + id).map(this.extractData).catch(this.handleError);
    }


    addUser(name:string) {
        // return this.http.post(this.userSaveUrl, body).toPromise();
        return this.http.post('user/save', 'name=' + name).map(res => res.json().data).catch(this.handleError);
    }

    delUser(id:number) {
        return this.http.get('user/delete?id=' + id).map(this.extractData).catch(this.handleError);
    }

    private extractData(res:Response) {
        let body = res.json();
        return body.data || {};
    }

    private handleError(error:any) {
        // In a real world app, we might use a remote logging infrastructure
        // We'd also dig deeper into the error to get a better message
        let errMsg = (error.message) ? error.message :
            error.status ? `${error.status} - ${error.statusText}` : 'Server error';
        console.error(errMsg); // log to console instead
        return Observable.throw(errMsg);
    }
}